package telbook;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ChangePassword
 */
public class ChangePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String oldpassword=request.getParameter("Opsd");
		String newpassword=request.getParameter("Npsd");
//		Cookie获取值
		Object name = null;
		Cookie[]cookies=request.getCookies();
		for(int i=0;cookies!=null&&i<cookies.length;i++)
		{
			if("userbean".equals(cookies[i].getName())){
				name=cookies[i].getValue();
				break;
			}
		}
		Object role=null;
		cookies=request.getCookies();
		for(int i=0;cookies!=null&&i<cookies.length;i++)
		{
			if("role".equals(cookies[i].getName())){
				role=cookies[i].getValue();
				break;
			}
		}
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
//			获取数据连接
			conn=JDBCUtils.getConnection();
//			获取Statement对象
			stmt=conn.createStatement();
//			发送SQL语句
			String sql="select password from "+role+" where name='"+name+"'";
			rs=stmt.executeQuery(sql);
			while(rs.next()) {
				if(oldpassword.equals(rs.getString("password"))) {
					sql="update "+role+" set password='"+newpassword+"' where name='"+name+"'";
					stmt.execute(sql);
					request.setAttribute("DBMes", "<p style='color:green'>密码修改成功</p>");
					request.getRequestDispatcher("/changePassword.jsp")
					.forward(request, response);
				}
				else {
					request.setAttribute("DBMes", "旧密码输入有误");
					request.getRequestDispatcher("/changePassword.jsp")
					.forward(request, response);
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
			request.setAttribute("DBMes", "您添加的信息已存在");
			request.getRequestDispatcher("/changePassword.jsp")
			.forward(request, response);
			
		}finally {
			JDBCUtils.release(rs, stmt, conn);
		}
	}

}
